<template>
  <div class="container">
    <el-dialog
      :title="title"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="closeDialog('formData')"
      custom-class="brand-dialog-min-width"
      :modal-append-to-body="false"
      :append-to-body="true"
      width="900px"
    >
      <el-form ref="formData" :model="formData">
        <el-form-item
          label="选择地区："
          class="row-padding-bottom mrT8"
          label-width="120px"
          prop="areaId"
          :rules="rules.areaId"
          v-if="
            role != 'LABOR_ADMIN' &&
            role != 'WAGE_SUPERVISOR' &&
            operate != 'edit'
          "
        >
          <el-cascader
            class="dialogDoubleInp"
            ref="manageArea"
            v-model="formData.areaId"
            :options="areasOptions"
            @change="getAreaId"
            clearable
            filterable
            :props="{ checkStrictly: true }"
            :append-to-body="false"
          ></el-cascader>
        </el-form-item>
        <el-divider
          v-if="
            role != 'LABOR_ADMIN' &&
            role != 'WAGE_SUPERVISOR' &&
            operate != 'edit'
          "
        ></el-divider>
        <div>
          <div
            :class="
              role != 'LABOR_ADMIN' &&
              role != 'WAGE_SUPERVISOR' &&
              operate != 'edit'
                ? 'secondaryTitle secondaryTitleTheme mrT24'
                : 'secondaryTitle secondaryTitleTheme'
            "
          >
            {{ addList[role] || '--' + '信息' }}
          </div>
          <div v-for="(item, index) in formData.list" :key="index">
            <div class="info" v-if="!item.showEdit">
              <div class="nameinfo subbox">
                <span class="title">{{ addList[role] + '姓名：' }}</span>
                <span class="desc">{{ item.name }}</span>
              </div>
              <div class="telinfo subbox">
                <span class="title">电话号码：</span>
                <span class="desc">{{ item.tel }}</span>
              </div>
              <div class="handle subbox">
                <el-link icon="el-icon-edit" @click="showEditBox(index)"
                  >编辑</el-link
                >
                <el-link
                  v-if="formData.list && formData.list.length > 1"
                  style="margin-left: 16px"
                  @click="delIndex(index)"
                  icon="el-icon-delete"
                  >删除</el-link
                >
              </div>
            </div>
            <div class="editBox" v-else>
              <h3 class="mrB30">{{ '添加' + addList[role] + '信息' }}</h3>
              <el-form-item
                :label="addList[role] + '姓名：'"
                label-width="170px"
                :prop="'list.' + index + '.name'"
                class="mB0"
                :rules="rules.name"
              >
                <el-input
                  v-model="item.name"
                  autocomplete="off"
                  placeholder="请输入姓名"
                  class="ratioWidth dialogDoubleInp"
                  @blur="item.name = changeValue($event)"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="电话号码："
                label-width="170px"
                :prop="'list.' + index + '.tel'"
                class="mB0"
                :rules="rules.tel"
              >
                <el-input
                  v-model="item.tel"
                  autocomplete="off"
                  placeholder="请输入电话号码"
                  class="ratioWidth dialogDoubleInp"
                  @blur="item.tel = changeValue($event)"
                ></el-input>
              </el-form-item>
              <div style="padding-left: 170px">
                <el-button
                  class="funComBut saveBtn"
                  @click="toSaveInfo(index)"
                  v-sdc
                  >保存</el-button
                >
                <el-button class="funComBut" @click="toCancle(index)"
                  >删除</el-button
                >
              </div>
            </div>
          </div>
          <el-row @click.native="addLevel" class="addLevel">
            <span style="font-size: 25px">+</span>
            <span style="position: relative; top: -4px">{{
              '添加' + addList[role]
            }}</span>
          </el-row>
        </div>
        <!-- <div
          class="segmentSettingYes"
          v-for="(item, index) in formData.list"
          :key="index"
        >
          <el-form-item
            :label="addList[role] + '姓名'"
            label-width="170px"
            :prop="'list.' + index + '.name'"
            class="mB0"
            :rules="rules.name"
          >
            <el-input
              v-model="item.name"
              autocomplete="off"
              placeholder="请输入"
              class="ratioWidth"
              @blur="item.name = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="电话号码"
            label-width="170px"
            :prop="'list.' + index + '.tel'"
            class="mB0"
            :rules="rules.tel"
          >
            <el-input
              v-model="item.tel"
              autocomplete="off"
              placeholder="请输入"
              class="ratioWidth"
              @blur="item.tel = changeValue($event)"
            ></el-input>
            <span class="buttonBox">
              <img
                src="../../../static/img/deposit/add.png"
                alt=""
                class="funcBox"
                @click="add"
                v-show="index == formData.list.length - 1"
              />
              <img
                src="../../../static/img/deposit/reduce.png"
                alt=""
                class="funcBox mR12"
                v-show="index > 0"
                @click="del(index)"
              />
            </span>
          </el-form-item>
        </div> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog('formData')" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="toSave('formData')"
          class="save"
          :loading="isSaveLoading"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'

export default {
  name: 'fiveMembersConfList',
  props: ['role', 'operate', 'detailArr'],
  data() {
    var validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入姓名'))
      } else if (this.formData.list.length == 1) {
        callback()
      } else {
        var arr = []
        this.formData.list.forEach((item, index) => {
          if (item.name == value) {
            arr.push(index)
          }
        })
        if (arr.length > 1) {
          callback(new Error(value + '人员姓名重复'))
        } else {
          callback()
        }
      }
    }
    var validateTel = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入联系方式'))
      } else if (this.formData.list.length == 1) {
        callback()
      } else {
        var arr = []
        this.formData.list.forEach((item, index) => {
          if (item.tel == value) {
            arr.push(index)
          }
        })
        if (arr.length > 1) {
          callback(new Error(value + '联系方式重复'))
        } else {
          callback()
        }
      }
    }
    return {
      formVisible: true,
      formData: {
        list: [
          {
            name: '',
            tel: '',
            showEdit: true,
          },
        ],
        areaId: '',
      },
      rules: {
        areaId: [{ required: true, message: '请选择区域', trigger: 'change' }],
        name: [{ required: true, validator: validateName, trigger: 'blur' }],
        tel: [
          { required: true, validator: validateTel, trigger: 'blur' },
          {
            pattern: /^\d{1,15}$/,
            message: '请输入长度在 15 个字以内的数字',
            trigger: 'blur',
          },
        ],
      },
      addList: {
        LABOR_ADMIN: '劳资专管员',
        WAGE_SUPERVISOR: '工资监督员',
        LABOR_SECURITY_INSPECTOR: '劳动保障监察员',
        LABOR_LAW_SUPERVISOR: '劳动法律监督员',
        PROJECT_SUPERVISOR: '项目监督员',
      },
      title: '',
    }
  },
  computed: { ...mapState(['areasOptions']) },
  created() {
    //编辑
    if (this.operate == 'edit') {
      this.editInit()
      this.title = '编辑' + this.addList[this.role]
    } else {
      this.title = '添加' + this.addList[this.role]
    }
  },
  methods: {
    toSaveInfo(index) {
      let validateList = []
      this.$refs['formData'].validateField(
        ['list.' + index + '.name', 'list.' + index + '.tel'],
        (error) => {
          validateList.push(error)
        }
      )
      if (validateList.every((item) => item === '')) {
        this.formData.list[index].showEdit = false
      }
    },
    toCancle(index) {
      if (this.formData.list.length > 1) {
        this.formData.list.splice(index, 1)
      }
    },
    showEditBox(index) {
      const findIndex = this.formData.list.findIndex((v) => v.showEdit)
      if (findIndex === -1) {
        this.formData.list.forEach((v, i) => {
          if (index === i) {
            v.showEdit = true
          } else {
            v.showEdit = false
          }
        })
      }
    },
    delIndex(index) {
      if (this.formData.list.length > 1) {
        this.formData.list.splice(index, 1)
      }
    },
    addLevel() {
      const count = this.formData.list.reduce((pre, cur) => {
        pre += cur.showEdit ? 1 : 0
        return pre
      }, 0)
      if (count === 0) {
        let addObj = {
          name: '',
          tel: '',
          showEdit: true,
        }
        this.formData.list.push(addObj)
      }
    },
    editInit() {
      var areaArr = []
      if (this.detailArr.cityId) {
        areaArr.push(this.detailArr.cityId)
      }
      if (this.detailArr.countyId) {
        areaArr.push(this.detailArr.countyId)
      }
      if (this.detailArr.townId) {
        areaArr.push(this.detailArr.townId)
      }
      this.formData.areaId = areaArr
      this.formData.list = []
      this.detailArr.fiveSuperviseEmpVOList.forEach((item, index) => {
        this.formData.list.push({
          name: item.name,
          tel: item.tel,
          showEdit: false,
        })
      })
    },
    closeDialog() {
      this.$emit('closeDialog', '')
    },
    add() {
      this.formData.list.push({
        name: '',
        tel: '',
      })
    },
    del(index) {
      if (this.formData.list.length == 1) {
        return
      }
      this.formData.list.splice(index, 1)
    },
    toSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 判断是否选择到了区县一级
          if (this.role != 'LABOR_ADMIN' && this.role != 'WAGE_SUPERVISOR') {
            if (this.formData.areaId.length < 2) {
              this.$message({
                message: '地区请选择到县/区级',
                type: 'warning',
              })
              return
            }
          }

          this.save()
        } else {
          return false
        }
      })
    },
    save() {
      var data = {}
      var url = ''
      if (this.operate == 'edit') {
        url = 'api-e/fivesupervise/editRole'
        data = {
          batch: this.detailArr.batch,
          emps: JSON.stringify(this.formData.list),
          cityId: this.formData.areaId[0] || '',
          countyId: this.formData.areaId[1] || '',
          townId: this.formData.areaId[2] || '',
        }
      } else {
        url = 'api-e/fivesupervise/addRole'
        data = {
          role: this.role,
          emps: JSON.stringify(this.formData.list),
          cityId: this.formData.areaId[0] || '',
          countyId: this.formData.areaId[1] || '',
          townId: this.formData.areaId[2] || '',
        }
      }
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: this.operate == 'edit' ? '编辑成功' : '添加成功',
                type: 'success',
              })
              this.$emit('closeDialog', 'success')
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
  },
}
</script>

<style scoped lang="less">
//   添加样式
.segmentSettingYes {
  padding: 24px 0;
  background: #f5f7fb;
  margin-bottom: 12px;
  .projectCostBox {
    position: relative;
    .unit {
      position: absolute;
      right: 24px;
    }
  }
  .funcBox {
    width: 25px;
    height: 25px;
    margin: 0 8px;
    cursor: pointer;
  }
  .unlimitInput {
    width: 25%;
    min-width: 160px;
  }
  .unlimitSty {
    /deep/.el-input__inner {
      border: 0;
      background: #f5f7fb;
    }
  }
  .buttonBox {
    position: absolute;
    right: 22px;
    top: 7.5px;
  }
  .ratioWidth {
    width: 310px;
  }
}
.info {
  width: 100%;
  height: 54px;
  padding: 0 20px;
  background: #f8f9fb;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
  &:hover {
    box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.2);
  }
  .subbox {
    width: 40%;
    text-align: left;
    .title {
      font-family: SourceHanSansCN-Medium;
      font-size: 14px;
      color: #333333;
      font-weight: 500;
    }
    .desc {
      font-family: SourceHanSansCN-Regular;
      font-size: 14px;
      color: #666666;
      line-height: 18px;
      font-weight: 400;
    }
  }
  .handle {
    width: 20%;
    text-align: right;
  }
}
.editBox {
  background: #f8f9fb;
  padding: 20px;
  margin-top: 10px;
  h3 {
    font-family: SourceHanSansCN-Bold;
    font-size: 14px;
    color: #275faa;
    font-weight: 700;
  }
}
.addLevel {
  height: 32px;
  text-align: center;
  line-height: 30px;
  font-size: 14px;
  color: #a3a3a3;
  border: 1px dashed #dee5f4;
  margin-top: 10px;
}
.addLevel:hover {
  cursor: pointer;
  color: #409eff;
  border-color: #409eff;
}
.funComBut {
  height: 30px;
  line-height: 30px;
  padding: 0 20px;
}
</style>
